package com.witframework.util;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/** @pdOid 81f9f0f5-cd4f-4bb8-b4e8-a02ae93d0336 */
public class TigerHtml {
	/**
	 * 查找html元素，要查找的元素不包含子元素和文本值， 如：&lt;input name="attribute\" type=\"text\"&gt 要获取以上元素，用法如下：
	 * <code>findInputFieldTag("attribute", htmlDocumentSource);</code>
	 * <P>
	 * <B>注意：该方法返回一个不完整的元素字符串表达， 以上的例子返回值为:&lt;input name="attribute\"</B>
	 * 
	 * @param name
	 * @param value
	 * @param htmlDocumentSource
	 * @return --如：&lt;input name="attribute\"
	 * @pdOid ef590a97-7ebd-4abf-97d2-82b20b613407
	 */
	public static String findInputFieldTag(String name, String value, String htmlDocumentSource) {
		
		Pattern p = Pattern.compile("<{1}([\\w\\W&&[^>]])*" + name + "[\\p{Punct}\\p{Blank}]*(" + value + ")(\\S)*\"{1}");
		Matcher m = p.matcher(htmlDocumentSource);
		if (m.find()) {
			return m.group().trim();
		}
		return null;
	}

	/**
	 * * 返回指定元素的后面是否含有img,如果有，返回html,否则返回""
	 * 
	 * @param name
	 * @param value
	 * @param htmlDocumentSource
	 * @pdOid 94a9e918-ef56-4e7c-a9cb-17a1f42a71d9
	 */
	public static String findInputFieldImg(String name, String value, String htmlDocumentSource) {
		String tmpHtml = null;
		String imgHtml = null;
		Pattern p;// = Pattern.compile("<{1}([\\p{Print}&&[^>]])*" + name + "[\\p{Punct}\\p{Blank}]*" + value + "([\\p{Print}&&[^>]])*(>){1}");
		p = Pattern.compile("<{1}([\\w\\W&&[^>]])*" + name + "[\\p{Punct}\\p{Blank}]*" + value + "([\\w\\W&&[^>]])*(>){1}");
		Matcher m = p.matcher(htmlDocumentSource);
		if (m.find()) {
			// return m.group().trim();
			tmpHtml = m.group().trim();
			htmlDocumentSource = htmlDocumentSource.substring(htmlDocumentSource.indexOf(tmpHtml), htmlDocumentSource.length() - 1);
			imgHtml = getHtmlElement("img", "", htmlDocumentSource);
			return imgHtml;
		}
		return null;

	}

	/**
	 * 查找html元素，要查找的元素不包含子元素和文本值， 如：<code>&lt;input name="attribute\" type=\"text\"&gt;</code>
	 * <P>
	 * 要获取以上元素，用法如下： <code>getHtmlElement("attribute", htmlDocumentSource);</code>
	 * 
	 * @param name
	 * @param value
	 * @param htmlDocumentSource
	 * @return -如：&lt;input name= "name" value="wxy"/&gt;
	 * @pdOid 60b0857b-5bba-4bac-ac3f-edb87b2cfad8
	 */
	public static String getHtmlElement(String name, String value, String htmlDocumentSource) {
		Pattern p ;//= Pattern.compile("<{1}([\\p{Print}&&[^>]])*" + name + "[\\p{Punct}\\p{Blank}]*" + value + "([\\p{Print}&&[^>]])*(>){1}");
		p = Pattern.compile("<{1}([\\w\\W&&[^>]])*" + name + "[\\p{Punct}\\p{Blank}]*" + value + "([\\w\\W&&[^>]])*(>){1}");
		Matcher m = p.matcher(htmlDocumentSource);
		if (m.find()) {
			return m.group().trim();
		}
		return null;
	}

	public static String getHtmlElement(String type,String name, String value, String htmlDocumentSource) {
		Pattern p ;//= Pattern.compile("<{1}([\\p{Print}&&[^>]])*" + name + "[\\p{Punct}\\p{Blank}]*" + value + "([\\p{Print}&&[^>]])*(>){1}");
		p = Pattern.compile("<{1}([\\w\\W&&[^>]])*"+type+"([\\w\\W&&[^>]])*" + name + "[\\p{Punct}\\p{Blank}]*" + value + "([\\w\\W&&[^>]])*(>){1}");
		Matcher m = p.matcher(htmlDocumentSource);
		if (m.find()) {
			return m.group().trim();
		}
		return null;
	}
	/**
	 * < input name="name" value="we"/>返回:"input"
	 * 
	 * @param tag
	 * @return
	 * @pdOid f08119d7-986f-4d18-8a4f-6d3cf9feb38f
	 */
	public static String getHtmlElementType(String tag) {
		Pattern p = Pattern.compile("<{1}\\p{Blank}*([\\p{Print}&&[^\\p{Blank}]])+\\p{Blank}{1}");
		Matcher m = p.matcher(tag);
		if (m.find()) {
			return m.group().trim().substring(1).trim();
		}
		return null;
	}

	/**
	 * 获取具有包含内容的html元素，
	 * <P>
	 * 如：&lt;select name="xb"&gt;&lt;option value=1 selected>男&lt;/option&gt;&lt;option value=0&gt;女&lt;/option&gt;
	 * &lt;/select&gt;
	 * <P>
	 * 要获取以上内容可通过：<code>getHtmlElement("select","name","xb",htmlDocumentSource)</code>
	 * 
	 * @param type
	 * @param name
	 * @param value
	 * @param htmlDocumentSource
	 * @return exm.:
	 * @see #
	 * @pdOid 65f89604-1bd5-4c6d-a52d-23ff0c40d4a9
	 */
	public static String getContainHtmlElement(String type, String name, String value, String htmlDocumentSource) {
		String src = htmlDocumentSource.replaceAll("([\n]){1}", "#&N;");
		src = src.replaceAll("([\r]){1}", "#&R;");
		// Pattern p =
		// Pattern.compile("<{1}\\p{Blank}*"+type+"\\p{Blank}*([\\p{Print}&&[^>]])*"+name+"[\\p{Punct}\\p{Blank}]*"+value+"(.)*(/"+type+")>{1}");
		Pattern p = Pattern.compile("<{1}\\p{Blank}*" + type + "\\p{Blank}*(.)*" + name + "[\\p{Punct}\\p{Blank}]*" + value);

		Matcher m = p.matcher(src);
		if (m.find()) {
			int start = m.start();
			String g = m.group().trim();
			int end = src.indexOf("/" + type + ">", start);
			String result = src.substring(src.indexOf(g), end + type.length() + 2);
			result = result.replaceAll("#&N;", "\n");
			result = result.replaceAll("#&R;", "\r");
			return result;
		}

		return null;
	}

	/**
	 * @param type
	 * @param htmlDocumentSource
	 * @pdOid b847de82-4729-4e96-b222-f3257163b85a
	 */
	public static String[] getChildrenHtmlElement(String type, String htmlDocumentSource) {
		List l = new ArrayList();
		String src = htmlDocumentSource.replaceAll("([\n]){1}", "#&N;");
		src = src.replaceAll("([\r]){1}", "#&R;");
		Pattern p = Pattern.compile("<{1}" + type + "(\\p{Blank})+([\\S\\s&&[^/]])*</" + type + ">");
		Matcher m = p.matcher(src);
		while (m.find()) {
			String g = m.group().trim();
			g = g.replaceAll("#&N;", "\n");
			g = g.replaceAll("#&R;", "\r");
			l.add(g);
		}
		return (String[]) l.toArray(new String[0]);
	}

	/**
	 * @param optionElement
	 * @pdOid 1652cd13-a1e6-4d83-aafa-29a403b442b1
	 */
	public static String getOptionValue(String optionElement) {
		optionElement=optionElement.replaceAll("'","\"");
		int b = optionElement.indexOf("\"");
		if (b > 0) {
			int e = optionElement.indexOf("\"", b + 1);
			if (e > b)
				return optionElement.substring(b + 1, e);
		} else {
			b = optionElement.indexOf("=");
			if (b > 0) {
				int e = optionElement.indexOf(" ", b + 1);
				if (e > b)
					return optionElement.substring(b + 1, e);
			}
		}
		return "";
	}
	
	public static boolean getOptionSelected(String optionElement) {
		int index = optionElement.toLowerCase().indexOf(" selected");
		if (index > -1) {
			return true;
		}
		return false;
	}
	public static String replaceIgnoreCase(String src,String target, String replacement){	
		String result="";
		String us=src.toUpperCase();
		String tempUus=us;
		while(us.indexOf(target.toUpperCase())>-1){		
			result+=src.substring(0,us.indexOf(target.toUpperCase()))+replacement;			
			src=src.substring(src.substring(0,us.indexOf(target.toUpperCase())).length()+target.length());
			us=src.toUpperCase();
		}
		return result+src;
	}
	public static String resetElementNameToLowerCase(String htmlDocumentSource){
		htmlDocumentSource=replaceIgnoreCase(htmlDocumentSource,"form","form");
		htmlDocumentSource=replaceIgnoreCase(htmlDocumentSource,"onsbumit","onsbumit");
		htmlDocumentSource=replaceIgnoreCase(htmlDocumentSource,"input","input");
		htmlDocumentSource=replaceIgnoreCase(htmlDocumentSource,"select","select");
		htmlDocumentSource=replaceIgnoreCase(htmlDocumentSource,"textarea","textarea");
		htmlDocumentSource=replaceIgnoreCase(htmlDocumentSource,"option","option");
		htmlDocumentSource=replaceIgnoreCase(htmlDocumentSource,"checkbox","checkbox");
		htmlDocumentSource=replaceIgnoreCase(htmlDocumentSource,"readio","readio");		
		return htmlDocumentSource;		
	}
	/**
	 * @param argv
	 * @exception Exception
	 * @pdOid ecd0a275-42ee-43de-b5d0-daa4f114194a
	 */
	public static void main(String[] argv) throws Exception {
		
		String htmlDocumentSource = ""
				+ "<html><body>"
				+ "<form name=\"testForm\">"
				+ "<input type=\"text\" maxlength=\"60\" size=\"30\" name=\"_c_email\" dataType=\"Email\" msg=\"信箱格式不正确\" require=\"true\" >"
				+ "<img src=\"\" />"
				+ "<input type=\"text\" value=\"老虎\" name= \"name\" />"
				+ "<img src=\"\" />"
				+ "<SELECT dbisnull=\"Yes\" dblength=\"20\" dbname=\"阿苏大\" dbpropertytype=\"text\" dbusertype=\"enum\" id=\"FIELD_21EP3\" name=\"asuda_CLST6\" dataType=\"LimitB\" msg=\"限制输入的字节长度,最大20个字节\"  max=\"20\"  title=\"阿苏大\">"

				+ "<OPTION selected value='阿苏大'>阿苏大</OPTION>"

				+ "<OPTION value=\"阿苏大三\">阿苏大三</OPTION>"

				+ "<OPTION value=\"琐琐碎碎\">琐琐碎碎</OPTION>" + "</SELECT>" + "<select name=\"_c_zw\"> \n "
				+ "<option value=1 selected>as</option><option value=0>df</option>" + "</SELECT>" + "<input tyep=s name=\"qq\" value=\"老虎\"/>"
				+ "<input type=\"checkbox\" checked=\"checked\" value=\"checkboxValue1\" name=\"checkbox\" />"
				+ "<input type=\"checkbox\" checked=\"checked\" value=\"checkboxValue2\" name=\"checkbox\" />"
				+ "</form>" + "</body></html>";
		htmlDocumentSource=resetElementNameToLowerCase(htmlDocumentSource);
		System.out.println("htmlDocumentSource=");
		System.out.println(htmlDocumentSource);
		System.out.println("=============================================");

		String s = findInputFieldTag("name", "_c_email", htmlDocumentSource);
		System.out.println("nmae=_c_email的元素=");
		System.out.println(s);
		System.out.println("=============================================");

		s = findInputFieldTag("name", "name", htmlDocumentSource);
		System.out.println("nmae=name的元素=");
		System.out.println(s);
		System.out.println("=============================================");

		s = getHtmlElement("name", "qq", htmlDocumentSource);
		System.out.println("nmae=qq的元素=");
		System.out.println(s);
		System.out.println();
		System.out.println("元素类型：" + getHtmlElementType(s));
		System.out.println("=============================================");
		
		System.out.println("名为testFrom的form元素");
		System.out.println(getContainHtmlElement("form", "name", "testForm", htmlDocumentSource));
		System.out.println("=============================================");
		
		System.out.println("名为asuda_CLST6的select元素");
		String select = getContainHtmlElement("select", "name", "asuda_CLST6", htmlDocumentSource);		
		System.out.println(select);
		System.out.println("Option子元素：");
		System.out.println(getChildrenHtmlElement("option", select)[0]);
		System.out.println(getChildrenHtmlElement("option", select)[1]);
		System.out.println(getOptionValue(getChildrenHtmlElement("option", select)[0]));
		System.out.println("=============================================");
		
		
		// htmlDocumentSource.replaceAll("<img src=\"\" />", " ");
		// System.out.println(htmlDocumentSource);
		// System.out.println(findInputFieldTag("img","",htmlDocumentSource));
	}

}